package com.hontech.pastacooking.net

import com.hontech.pastacooking.app.NetTask
import com.hontech.pastacooking.app.log

class ConnectTask : Runnable {

    companion object {

        fun connect(delayMs: Long = 0) {
            NetTask.postDelayed(ConnectTask(), delayMs)
        }
    }

    override fun run() {

        try {
            exec()
        } catch (e: Exception) {
            e.printStackTrace()
            NetTask.postDelayed(this, 10 * 1000L)
        }
    }

    private fun exec() {
        val socket = NIOSocket.connect(HOST, PORT)
        try {
            val req = WriteFrame.makeJson(REQ_CONNECT, ConnectReq())
            socket.write(req)
            val res = socket.read().parseJson<ConnectRes>()
            NetClient(socket, res)
        } catch (e: Exception) {
            e.printStackTrace()
            socket.close()
            throw e
        }

        log("net 连接成功")
    }
}


